package com.kajespero.webapp.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;

import com.kajespero.service.user.UserService;
import com.kajespero.service.user.impl.UserServiceImpl;
import com.kajespero.vo.UserVO;
import com.kajespero.webapp.AttributesConstants;

public class GoogleAppRequestServletListener implements ServletRequestListener {
	
	private static final UserService USER_SERVICE = new UserServiceImpl();

	@Override
	public void requestDestroyed(ServletRequestEvent sre) {
		HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
		UserVO administrator = (UserVO) request.getSession().getAttribute(AttributesConstants.ADMINISTRATOR);
		if(administrator != null){
			administrator = USER_SERVICE.find(administrator.getId());
			request.getSession().setAttribute(AttributesConstants.ADMINISTRATOR, administrator);
		}
	}

	@Override
	public void requestInitialized(ServletRequestEvent sre) {
		HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
		UserVO administrator = (UserVO) request.getSession().getAttribute(AttributesConstants.ADMINISTRATOR);
		if(administrator != null){
			administrator = USER_SERVICE.find(administrator.getId());
			request.getSession().setAttribute(AttributesConstants.ADMINISTRATOR, administrator);
		}
	}
}
